//
//  AutomationCell.m
//  OST
//
//  Created by mac on 13-7-6.
//  Copyright (c) 2013年 mac. All rights reserved.
//

#import "AutomationCell.h"
#import "GlobalVar.h"
#import "WISInterfaces.h"
#import "wis.h"
#import "MBProgressHUD.h"
#import "Utitlity.h"
#import "NSString+Utils.h"
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>

typedef NS_ENUM(NSInteger, AutomationDoorLockMode) {
    
    AutomationDoorLockModeUnsecured = 0,
    AutomationDoorLockModeUnsecured_Timeout = 1,
    AutomationDoorLockModeInside_Unsecured = 16,
    AutomationDoorLockModeInside_Unsecured_Timeout = 17,
    AutomationDoorLockModeOutside_Unsecured = 32,
    AutomationDoorLockModeOutside_Unsecured_Timeout = 33,
    AutomationDoorLockModeSecured = 255,
};

@interface AutomationCell () <MBProgressHUDDelegate> {
    MBProgressHUD *_hud;
    NSString *ipUrl;
    AVAudioPlayer *soundPlayer;
    float volume;
    
    NSInteger binarySwitchValue;
    NSInteger multiLevelSwitchValue;
    NSInteger binarySensorValue;
    AutomationDoorLockMode doorLockModeVal;
    
    int channel;
    
    AutomationType automationType;
    
}
@end
@implementation AutomationCell

-(void)dealloc
{
    self.httpRequest.delegate = nil;
    [self.httpRequest cancel];
}

-(void)initView
{    
    binarySwitchValue = 0 ;
    multiLevelSwitchValue = 0;
    //multiLevelSwitchNewValue = 0;
    channel = 0;
    
    UIImage *img1  = [UIImage imageNamed:@"bg_cell"];
    UIImage *img2  = [UIImage imageNamed:@"bg_cell_sel"];
    
    UIImageView *cellbg1 = [[UIImageView alloc]initWithImage:img1];
    UIImageView *cellbg2 = [[UIImageView alloc]initWithImage:img2];
    
    self.backgroundView = cellbg1;
    self.selectedBackgroundView = cellbg2;
    
    [self.btnSensorBetterLv setImage:[UIImage imageNamed:@"battery_normal"] forState:UIControlStateNormal];
    [self.btnSensorBetterLv setImage:[UIImage imageNamed:@"battery_low"] forState:UIControlStateSelected];
    
   
}

//- (void)getTryAutoMationInfo:(NSDictionary *)mdata
//{
//    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
//    NSString *uuid = [[mdata objectForKey:@"muuid"] lowercaseString];
//    if ([user objectForKey:@"uuid"] == nil) {
//        NSInteger deviceType = [[mdata objectForKey:@"DeviceType"] integerValue];
//        if (deviceType == AutomationTypeBinarySwitch) {
////            info.icon= @"icon_light1_";
//            [user setObject:@"icon_light1_" forKey:@"micon"];
//        }else if (deviceType == AutomationTypeMultiLvSwitch) {
////            info.icon= @"icon_light2_";  //icon_socket_
//            [user setObject:@"icon_light2_" forKey:@"micon"];
//        }else if (deviceType == AutomationTypeBinarySensor) {
////            info.icon= @"icon_sensor_";
//             [user setObject:@"icon_sensor_" forKey:@"micon"];
//            
//        }else if (deviceType == AutomationTypeMultiLvSensor) {
//            
//            NSInteger sensorType = [[mdata objectForKey:@"SensorType"] integerValue];
//            if (sensorType == 1) {
////                info.icon = @"sensor_climate";
//                [user setObject:@"sensor_climate" forKey:@"micon"];
//            }else
////                info.icon = @"sensor_climate";
//             [user setObject:@"sensor_climate" forKey:@"micon"];
//            
//        }else if (deviceType == AutomationTypeMotorCurtain) {
////            info.icon = @"window_";
//            [user setObject:@"window_" forKey:@"micon"];
//        }
//        
////        info.uuid = uuid;
//        [user setObject:uuid forKey:@"muuid"];
//        [user setObject:[mdata objectForKey:@"ZID"] forKey:@"mzid"];
////        info.name = [mdata objectForKey:@"Alias"];
//        [user setObject:[mdata objectForKey:@"Alias"] forKey:@"m"]
//    }
//    
//}

+(PersistableInfo *)getAutoMationInfo:(NSDictionary *)mdata
{
    
    __block PersistableInfo *info;
   
    dispatch_sync([GlobalInfo sharedInstance].sql_queue, ^{
        NSString *uuid = [[mdata objectForKey:@"uuid"] lowercaseString];
        
        info = (PersistableInfo *)[PersistableInfo findFirstByCriteria:@"where uuid='%@'",uuid];
        
        if (!info)
        {
            info = [[PersistableInfo alloc]init];
            
            NSInteger deviceType = [[mdata objectForKey:@"DeviceType"] integerValue];
            if (deviceType == AutomationTypeBinarySwitch) {
                info.icon= @"icon_light1_";
            }else if (deviceType == AutomationTypeMultiLvSwitch) {
                info.icon= @"icon_light2_";  //icon_socket_
            }else if (deviceType == AutomationTypeBinarySensor) {
                info.icon= @"icon_sensor_";
            }else if (deviceType == AutomationTypeMultiLvSensor) {
                
                NSInteger sensorType = [[mdata objectForKey:@"SensorType"] integerValue];
                if (sensorType == 1) {
                    info.icon = @"sensor_climate";
                }else
                    info.icon = @"sensor_climate";
                
            }else if (deviceType == AutomationTypeDoorLock) {
             
                info.icon= @"icon_doorlock_";
                
            }else if (deviceType == AutomationTypeMotorCurtain) {
                info.icon = @"window_";
            }else{
                info.icon = @"unknow";
            }
            
            info.uuid = uuid;
            info.zid = [mdata objectForKey:@"ZID"];
            info.name = [mdata objectForKey:@"Alias"];
            [info save];
        }
    });
    return info;
    
}

#pragma mark -
-(void)updateIcon
{
    //NSString *kind = [[data objectForKey:@"kind"] lowercaseString];
    BOOL isDeviceNotAvailable = FALSE;
    NSInteger deviceStatus = [self.data getIntegerValForKey:@"Status"];
    if (deviceStatus == 99) isDeviceNotAvailable = TRUE;
    self.switcher.enabled = TRUE;
    self.slider.enabled = TRUE;
    
   PersistableInfo *info= [AutomationCell getAutoMationInfo:self.data];

    NSInteger value = 0;
    if (automationType == AutomationTypeBinarySwitch || automationType == AutomationTypeMeter){
        self.slider.hidden = YES;
        self.curtainCtrlView.hidden = YES;
        self.switcher.hidden = NO;
        value = binarySwitchValue;
        self.switcher.selected = (binarySwitchValue == 1 ? TRUE:FALSE);
        self.btnSensorBetterLv.hidden = TRUE;
        
    }else if(automationType == AutomationTypeMultiLvSwitch){
        
        value = multiLevelSwitchValue;
        self.switcher.hidden = YES;
        self.slider.hidden = NO;
        self.curtainCtrlView.hidden = YES;
        self.slider.maximumValue = 99;
        self.slider.value = multiLevelSwitchValue;
        self.btnSensorBetterLv.hidden = TRUE;
        
        [self generateMultiLevelSwitchValueText:self.slider.value];
        
    }else if (automationType == AutomationTypeBinarySensor || automationType == AutomationTypeMultiLvSensor) {
      //Binary Sensor Status表示状态， 2表示触发, 3表示正常 99表示失效; Value暂无意义
    
      //MultiLevel Sensor的Status 3表示正常 99表示失效; Value根据SensorType判断
        self.switcher.selected = (binarySwitchValue == 1 ? TRUE:FALSE);
        
        //温度剂不可以修改
        if (automationType == AutomationTypeMultiLvSensor)
        {
            self.btnChangeInfo.enabled = FALSE;
        }
        else
        {
            self.btnChangeInfo.enabled = YES;
        }
        
        self.btnSensorBetterLv.hidden = FALSE;
        self.labelSensorTemperature.hidden = FALSE;
        
        NSInteger betterLv = [self.data getIntegerValForKey:@"BatteryLevel"];
        if (betterLv <= 20) {
            self.btnSensorBetterLv.selected = TRUE;
        }else
            self.btnSensorBetterLv.selected = FALSE;
        [self.btnSensorBetterLv setTitle:[NSString stringWithFormat:@"%d%%", betterLv] forState:UIControlStateNormal];
        
        NSString *valStr = [self.data objectForKey:@"Value"];
        if (valStr) {
            float a = [valStr floatValue];
            float   b  =   (float)(round(a*10))/10;
            self.labelSensorTemperature.text = [NSString stringWithFormat:@"%0.1f℃", b];
        }

        if (automationType == AutomationTypeBinarySensor) {
            if (deviceStatus == 2) {//2触发，3正常，99失效 ; 99使用和3正常一个图标
                value = 1;
            }
        }

    }else if (automationType == AutomationTypeMotorCurtain) {
        
        value = binarySwitchValue;
        self.btnChangeInfo.enabled = TRUE;
        self.curtainCtrlView.hidden = FALSE;
        self.switcher.hidden = YES;
        self.slider.hidden = YES;
        self.btnSensorBetterLv.hidden = TRUE;
        
    }else if(automationType == AutomationTypeDoorLock){
     
        value = doorLockModeVal;
        self.switcher.selected = (doorLockModeVal == 0 ? TRUE:FALSE);
        
    }else
    {
        self.btnChangeInfo.enabled = NO;
        self.curtainCtrlView.hidden = YES;
        self.switcher.hidden = YES;
        self.slider.hidden = YES;
        self.btnSensorBetterLv.hidden = TRUE;
    }
    
    if (automationType <= 3 || automationType == AutomationTypeMotorCurtain) {
        
        if (value != 0) {
            self.icon.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@open",info.icon]];
        }else {
            self.icon.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@close",info.icon]];
        }
        
    }else if (automationType == AutomationTypeMeter) {
    
        if (value != 0) {
            self.icon.image = [UIImage imageNamed:@"icon_socket_open"];
        }else {
            self.icon.image = [UIImage imageNamed:@"icon_socket_close"];
        }
        
    }else if (automationType == AutomationTypeDoorLock) {
        
        self.slider.hidden = YES;
        if (value == 0)
            self.icon.image = [UIImage imageNamed:@"icon_doorlock_open"];
        else
            self.icon.image = [UIImage imageNamed:@"icon_doorlock_close"];
    }else
        self.icon.image = [UIImage imageNamed:info.icon];

    
    if (isDeviceNotAvailable) {
    //5.23 email 状态无效也可以正常发送控制指令
        //self.switcher.enabled = FALSE;
        //self.slider.enabled = FALSE;
    }
    
    //if(automationType != AutomationTypeMultiLvSwitch)
        self.labelName.text = [[self.data objectForKey:@"Alias"] stringByDecodingURLFormat];
    
    if (deviceStatus == 99)
    {
        //self.icon.alpha = 0.3;
        //self.icon.backgroundColor = [UIColor blackColor];
    }
//    NSLog(@"value:%ld",(long)value);
    
}

-(void)generateMultiLevelSwitchValueText:(int)value
{
    PersistableInfo *info = [AutomationCell getAutoMationInfo:self.data];

    if (value==0){
        self.labelName.text = info.name;
    }else{
        self.labelName.text = [NSString stringWithFormat:@"%@(%d%%)",info.name,value] ;
    }
    
    /*
    int sensorId = [[self.data objectForKey:@"sensorid"]intValue];
    if (sensorId==0){
        //self.slider.maximumValue = 10 ;
        value ++;
        self.labelName.text = [NSString stringWithFormat:@"%@(%d%%)",info.name,value*10] ;
    }else{
        //self.slider.maximumValue = 12 ;
        if (value==0){
            self.labelName.text = info.name;
        }else if (value==1){
            self.labelName.text = info.name;
        }else{
            self.labelName.text = [NSString stringWithFormat:@"%@(%d%%)",info.name,(value-2)*10] ;
        }
    }*/
}

-(void)setupInitValueToAutomationController:(NSDictionary *)status
{
    NSString *kind = [[status objectForKey:@"kind"] lowercaseString];
    int sensorId = [[status objectForKey:@"sensorid"]intValue];
    
    if ([kind isEqualToString:@"binaryswitch"]) {
        binarySwitchValue = [[status objectForKey:@"status"]intValue];
    }else if ([kind isEqualToString:@"multilevelswitch"]){
        if (sensorId==1){
            multiLevelSwitchValue = [[status objectForKey:@"status"]intValue];
        }else if (sensorId==2){
            NSString *bvalue = [self.data objectForKey:@"bvalue"];
            if ([bvalue isEqualToString:@"0"]) {
                multiLevelSwitchValue = 0 ;
            }else if ([bvalue isEqualToString:@"255"]) {
                multiLevelSwitchValue = 1 ;
            }else {
                int value = [[status objectForKey:@"value"]intValue]+ 2;
                if (value < 2) {
                    value = 2;
                }else if (value > 12) {
                    value = 12;
                }
                multiLevelSwitchValue = value;
            }
        }else if (sensorId==0){
            int value = [[status objectForKey:@"value"]intValue];
            if (value > 10) {
                value = 10;
            }else if (value < 0) {
                value = 0;
            }
            multiLevelSwitchValue = value;
        }
    }
    
    [self updateIcon];
}

-(void)setCellData:(NSDictionary *)thedata
{
    self.data = thedata;
    
    automationType = [self.data getIntegerValForKey:@"DeviceType"];
    switch (automationType) {
            
        case AutomationTypeMeter:
        case AutomationTypeBinarySwitch:
        case AutomationTypeMotorCurtain:
        {
            NSInteger val = [self.data getIntegerValForKey:@"Status"];
            if (val == 99) binarySwitchValue = 0;
            else binarySwitchValue = val;
            break;
        }
        case AutomationTypeMultiLvSwitch:
            multiLevelSwitchValue = [self.data getIntegerValForKey:@"Value"];
            break;
            
        case AutomationTypeDoorLock:
            doorLockModeVal = [self.data getIntegerValForKey:@"Status"];
            break;
            
        case AutomationTypeBinarySensor:
        case AutomationTypeMultiLvSensor:
        {
            BOOL val = [self.data getBooleanValForKey:@"Arm"];
            if (val == TRUE) binarySwitchValue = 1;
            else binarySwitchValue = 0;
            break;
        }
            
        default:
            break;
    }
    [self updateIcon];
}

- (void)promptErrMsg:(NSDictionary *)jsondata {
    NSString *promptMsg = nil;
    switch ([[jsondata objectForKey:@"info"] integerValue]) {
        case 501:
            promptMsg = @"被控端电器无回应！";
            break;
            
        case 502:
            promptMsg = @"无此ID设备！";
            break;
            
        case 503:
            promptMsg = @"账户密码认证错误！";
            break;
            
        case 506:
            promptMsg = @"处理错误！";
            break;
            
        case 509:
            promptMsg = @"命令无效！";
            break;
            
        default:
            break;
    }
    if (promptMsg) {
        
        _hud = [[MBProgressHUD alloc] initWithView:self.window.rootViewController.view];
        [self.window.rootViewController.view addSubview:_hud];
        
        _hud.delegate = self;
        _hud.labelText = promptMsg;
        _hud.removeFromSuperViewOnHide = YES;
        [_hud hide:YES afterDelay:1.0];
    }

}

- (void)sendCMDDevSwitchSetToServer:(NSInteger)value
{
    ipUrl = [Utitlity judgeipUrl];
    
    NSString *zid = [self.data objectForKey:@"ZID"];
    if (ipUrl)
    {
      NSString *urlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Switch.cgi?ZID=%@&Value=%d",ipUrl,zid,value];
        
        [Utitlity commonHTTPMethod:urlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            if (responseObject)
            {
                [self promptErrMsg:responseObject];
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
    else
    {
        WisDevSwitchSetCmd cmd;
        strcpy(cmd.uuid, [[[GlobalInfo sharedInstance] getUniqueID] UTF8String]);
        strcpy(cmd.did, [zid UTF8String]);
        cmd.value = value;
        
        [[CMDDataProcessor sharedInstance] sendCMDId:WIS_CMD_V2_DEV_SWITCH_SET cmdLength:sizeof(WisDevSwitchSetCmd)  withData:&cmd callRecivedBlock:^(id jsondata) {
            
            if (jsondata)
            {
                [self promptErrMsg:jsondata];
            }
        }];
    }
}

-(IBAction)performBinarySwitchAction:(id )sender
{
    [self buttonSelectedWithSound];
//    if (self.adelegate)
//    {
//        [self.adelegate startTimer];
//    }
    
    self.switcher.selected = !self.switcher.selected;
    
    if(automationType == AutomationTypeDoorLock) {
        
        [self sendCMDDevDoorLockOpen:self.switcher.selected];
        return;
        
    }else if (automationType == AutomationTypeBinarySwitch || automationType == AutomationTypeMeter) {
    
        binarySwitchValue = (self.switcher.selected)?1:0;
  
    }else if (automationType == AutomationTypeBinarySensor || automationType == AutomationTypeMultiLvSensor) {
        
        binarySwitchValue = (self.switcher.selected)?1:0;
        if (self.adelegate && [self.adelegate respondsToSelector:@selector(switcherOnChangedValue:data:cell:)])
        {
            [self.adelegate switcherOnChangedValue:binarySwitchValue data:self.data cell:self];
        }
        return;
    }
 
    [self sendCMDDevSwitchSetToServer:(self.switcher.selected?255:0)];
    [self.data setValue:[NSString stringWithFormat:@"%d",(self.switcher.selected?1:0)] forKey:@"Status"];
    
    [self updateIcon];
}

-(IBAction)onSeekBarChange:(id)sender
{
    [self buttonSelectedWithSound];
    
    multiLevelSwitchValue = (NSInteger)self.slider.value;
    [self.data setValue:[NSString stringWithFormat:@"%d",multiLevelSwitchValue] forKey:@"Value"];
    [self generateMultiLevelSwitchValueText:multiLevelSwitchValue];
    
    [self updateIcon];
}

-(IBAction)onSeekBarTouchUp:(id)sender
{
    [self buttonSelectedWithSound];
//    if (self.adelegate)
//    {
//        [self.adelegate startTimer];
//    }
    
    multiLevelSwitchValue = (int)self.slider.value;
    [self generateMultiLevelSwitchValueText:multiLevelSwitchValue];
    
    [self sendCMDDevSwitchSetToServer:multiLevelSwitchValue];
    
}

-(IBAction)changeInfo:(id)sender
{
    [self buttonSelectedWithSound];
    
    if (self.adelegate)
    {
        [self.adelegate changeInfo:self.data cell:self];
    }
}

//-(void)open
//{
//    ipUrl = [Utitlity judgeipUrl];
//    if (ipUrl)
//    {
//        NSString *openStr = [NSString stringWithFormat:@"http://%@/cgi-bin/SwitchAll.cgi?OP=1",ipUrl];
//        [Utitlity commonHTTPMethod:openStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
//            NSLog(@"responseType:%@",responseObject);
//            if (self.slider.hidden) {
//                if (self.switcher.selected) {
//                    return;
//                }
//                self.switcher.selected = YES;
//                 NSInteger deviceType = [[self.data objectForKey:@"DeviceType"] integerValue];
//                if (deviceType == AutomationTypeBinarySwitch) {
//                    binarySwitchValue = 1;
//                }else{
//                    multiLevelSwitchValue= 9;
//                }
//            }else{
//                if (self.slider.value == self.slider.maximumValue) {
//                    return;
//                }
//                
//                self.slider.value = self.slider.maximumValue;
//                multiLevelSwitchValue = (int)self.slider.value;
//                [self generateMultiLevelSwitchValueText:multiLevelSwitchValue];
//            }
//        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//            NSLog(@"error:%@",error);
//        }];
//    }
////    if (self.slider.hidden) {
////        if (self.switcher.selected) {
////            return;
////        }
////        self.switcher.selected = YES;
////        NSString *kind = [[self.data objectForKey:@"kind"] lowercaseString];
////        if ([kind isEqualToString:@"binaryswitch"]) {
////            binarySwitchValue = 1;
////        }else{
////            multiLevelSwitchValue= 9;
////        }
////    }else{
////        if (self.slider.value == self.slider.maximumValue) {
////            return;
////        }
////        
////        self.slider.value = self.slider.maximumValue;
////        multiLevelSwitchValue = (int)self.slider.value;
////        [self generateMultiLevelSwitchValueText:multiLevelSwitchValue];
////    }
////    
////    self.httpRequest = [self createHTTPRequest];
////    [self.httpRequest startAsynchronous];
//    
//}


//-(void)close
//{
//    ipUrl = [Utitlity judgeipUrl];
//    if (ipUrl)
//    {
//        NSString *openStr = [NSString stringWithFormat:@"http://%@/cgi-bin/SwitchAll.cgi?OP=2",ipUrl];
//        [Utitlity commonHTTPMethod:openStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
//            NSLog(@"responseType:%@",responseObject);
//            if (self.slider.hidden)
//            {
//                if (!self.switcher.selected)
//                {
//                    return;
//                }
//                self.switcher.selected = NO;
//                 NSInteger deviceType = [[self.data objectForKey:@"DeviceType"] integerValue];
//                if (deviceType == AutomationTypeBinarySwitch)
//                {
//                    binarySwitchValue = 0;
//                }
//                else
//                {
//                    multiLevelSwitchValue= 0;
//                }
//            }
//            else
//            {
//                if (self.slider.value == 0)
//                {
//                    return;
//                }
//                self.slider.value = 0;
//                
//                multiLevelSwitchValue = (int)self.slider.value;
//                [self generateMultiLevelSwitchValueText:multiLevelSwitchValue];
//            }
//        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//            NSLog(@"error:%@",error);
//        }];
//    }
//    
////    if (self.slider.hidden) {
////        if (!self.switcher.selected) {
////            return;
////        }
////        self.switcher.selected = NO;
////        NSString *kind = [[self.data objectForKey:@"kind"] lowercaseString];
////        if ([kind isEqualToString:@"binaryswitch"]) {
////            binarySwitchValue = 0;
////        }else{
////            multiLevelSwitchValue= 0;
////        }
////    }else{
////        if (self.slider.value == 0) {
////            return;
////        }
////        self.slider.value = 0;
////        multiLevelSwitchValue = (int)self.slider.value;
////        [self generateMultiLevelSwitchValueText:multiLevelSwitchValue];
////    }
////    
////    self.httpRequest = [self createHTTPRequest];
////    [self.httpRequest startAsynchronous];
//}

- (IBAction)curtainCtrlClose:(id)sender {
    
//    if (self.adelegate)
//    {
//        [self.adelegate startTimer];
//    }
    [self buttonSelectedWithSound];
    binarySwitchValue = 0;
    [self.data setValue:[NSString stringWithFormat:@"%d",binarySwitchValue] forKey:@"Status"];
    [self sendCMDDevSwitchSetToServer:0];
    [self updateIcon];
}

- (void)curtainCtrlClocsed
{
    [self buttonSelectedWithSound];
    binarySwitchValue = 0;
    [self.data setValue:[NSString stringWithFormat:@"%d",binarySwitchValue] forKey:@"Status"];
    [self sendCMDDevSwitchSetToServer:0];
    [self updateIcon];
}

- (IBAction)curtainCtrlOpen:(id)sender {
    
//    if (self.adelegate)
//    {
//        [self.adelegate startTimer];
//    }
     [self buttonSelectedWithSound];
    binarySwitchValue = 1;
    [self.data setValue:[NSString stringWithFormat:@"%d",binarySwitchValue] forKey:@"Status"];
    [self sendCMDDevSwitchSetToServer:1];
    [self updateIcon];
}
- (void)curtainCtrlOpened
{
    [self buttonSelectedWithSound];
    binarySwitchValue = 1;
    [self.data setValue:[NSString stringWithFormat:@"%d",binarySwitchValue] forKey:@"Status"];
    [self sendCMDDevSwitchSetToServer:99];
    [self updateIcon];
}

- (IBAction)curtainCtrlStop:(id)sender {
    [self buttonSelectedWithSound];
    binarySwitchValue = 0;
    [self.data setValue:[NSString stringWithFormat:@"%d",binarySensorValue] forKey:@"Status"];
    [self sendCMDDevSwitchSetToServer:-1];
}

#pragma mark -
////xuyao 修改
//-(ASIHTTPRequest *)createHTTPRequest
//{
//    NSString *url = @"";
//    NSString *zid = [self.data objectForKey:@"zid"];
//    NSString *kind = [[self.data objectForKey:@"kind"] lowercaseString];
//    
//    if ([kind isEqualToString:@"binaryswitch"]) {
//        int mid = [[self.data objectForKey:@"mid"]intValue];
//        NSString *xchannel = [self.data objectForKey:@"channel"];
//        if (mid ==0){
//            url = [NSString stringWithFormat:@"cgi-bin/Switch.cgi?ZID=%@&OP=%d",zid,binarySwitchValue];
//        }else{
//            url = [NSString stringWithFormat:@"cgi-bin/Switch.cgi?ZID=%@&OP=%d&Inst=%@",zid,binarySwitchValue,([xchannel isEqualToString:@"1"]?@"":xchannel)];
//        }
//    }else if ([kind isEqualToString:@"multilevelswitch"]){
//        int sensorId = [[self.data objectForKey:@"sensorid"]intValue];
//        if (sensorId ==1 ){
//            url = [NSString stringWithFormat:@"cgi-bin/Switch.cgi?ZID=%@&VALUE=%d",zid,multiLevelSwitchValue];
//        }else if (sensorId==2){
//            int newValue = multiLevelSwitchValue;
//            if (newValue == 0) {//off
//                url = [NSString stringWithFormat:@"cgi-bin/Switch.cgi?ZID=%@&OP=%d&VALUE=%d",zid,7,0];
//            }else if (newValue == 1) {//on
//                url = [NSString stringWithFormat:@"cgi-bin/Switch.cgi?ZID=%@&OP=%d&VALUE=%d",zid,7,255];
//            }else if (newValue>1 && newValue<12) {
//                url = [NSString stringWithFormat:@"cgi-bin/Switch.cgi?ZID=%@&VALUE=%d",zid,newValue];
//            }
//        }else if (sensorId==0){
//            int newValue = multiLevelSwitchValue;
//            url = [NSString stringWithFormat:@"cgi-bin/Switch.cgi?ZID=%@&VALUE=%d",zid,newValue];
//        }
//    }
//    
//    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[GlobalVar createApiUrlAddress:url]]];
//    request.delegate = self;
//    request.username = [GlobalVar getDataForKey:@"config.username"];
//    request.password = [GlobalVar getDataForKey:@"config.password"];
//    [request setAuthenticationScheme:(NSString *)kCFHTTPAuthenticationSchemeBasic];
//    return request;
//}
//
//- (void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)xdata
//{
//    NSString *dataString = [[NSString alloc]initWithData:xdata encoding:NSUTF8StringEncoding];
//    dataString = [dataString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//    dataString = [dataString lowercaseString];
//    
//    NSString *kind = [[self.data objectForKey:@"kind"] lowercaseString];
//    int sensorId = [[self.data objectForKey:@"sensorid"]intValue];
//    
//    if ([kind isEqualToString:@"binaryswitch"] || ([kind isEqualToString:@"multilevelswitch"] && sensorId==1)){
//        if ([dataString isEqualToString:@"success"]) {
//            [self updateIcon];
//        }else{
//            self.switcher.selected = !self.switcher.selected;
//        }
//    }else if([kind isEqualToString:@"multilevelswitch"] && (sensorId==2 ||  sensorId==0)){
//        if ([dataString isEqualToString:@"success"]) {
//            multiLevelSwitchValue =  multiLevelSwitchValue;
//            [self updateIcon];
//        }else{
//            [self generateMultiLevelSwitchValueText:multiLevelSwitchValue];
//            self.slider.value = multiLevelSwitchValue;
//        }
//    }
//}


//after selected button,sound play
- (void)buttonSelectedWithSound
{
//    float svolume = 0.0;
//    UInt32 dataSize = sizeof(float);
//    OSStatus status = AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareOutputVolume,
//                                               &dataSize,
//                                               &svolume);
    
    volume = 0.1;
    //volume
    NSURL *url = [NSURL URLWithString:@"/System/Library/Audio/UISounds/Tock.caf"];
    soundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    soundPlayer.numberOfLoops = 1;
//    volume = 0.3f;
    soundPlayer.volume = volume;
    [soundPlayer prepareToPlay];
    [soundPlayer play];
}


#pragma mark - 门锁 Door Lock
- (void)sendCMDDevDoorLockSetToServer:(NSInteger)value
{
    ipUrl = [Utitlity judgeipUrl];
    
    NSString *zid = [self.data objectForKey:@"ZID"];
    if (ipUrl)
    {
        NSString *urlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Door.cgi?action=do_setmode&did=%@&mode=%ld",ipUrl,zid,value];
        
        [Utitlity commonHTTPMethod:urlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            if ( ![[[responseObject objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
                [self promptErrMsg:responseObject];
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
    else
    {
        WisDevSwitchSetCmd cmd;
        strcpy(cmd.uuid, [[[GlobalInfo sharedInstance] getUniqueID] UTF8String]);
        strcpy(cmd.did, [zid UTF8String]);
        cmd.value = value;
        
        [[CMDDataProcessor sharedInstance] sendCMDId:WIS_CMD_V2_DEV_SWITCH_SET cmdLength:sizeof(WisDevSwitchSetCmd)  withData:&cmd callRecivedBlock:^(id jsondata) {
            
            if (jsondata)
            {
                [self promptErrMsg:jsondata];
            }
        }];
    }
}

- (void)sendCMDDevDoorLockOpen:(BOOL)isOpen
{
    ipUrl = [Utitlity judgeipUrl];
    
    NSString *zid = [self.data objectForKey:@"ZID"];
    if (ipUrl)
    {
        NSString *urlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Door.cgi?action=do_ctrl&did=%@&open=%@",ipUrl,zid, (isOpen?@"False":@"True")];
        
        [Utitlity commonHTTPMethod:urlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            if ([[[responseObject objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
                
                doorLockModeVal = (isOpen == TRUE ? 0: 255);
                [self.data setValue:[NSString stringWithFormat:@"%ld",doorLockModeVal] forKey:@"Status"];
                 [self updateIcon];
                
            }else{
                [self promptErrMsg:responseObject];
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
    
}

@end
